package com.websocket.config;

import com.websocket.WebSocketConfig;
import com.websocket.exception.service.ExceptionDispatch;
import com.websocket.service.WebSocketServer;
import com.websocket.service.dispatch.WebSocketDispatch;
import com.websocket.service.WebSocketTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Import;

@AutoConfiguration
@Import(WebSocketBeanInitializer.class)
public class WebsocketConfigurer {

    @Autowired
    public WebsocketConfigurer(@Autowired(required = false) DefaultWebSocketConfigurer configurer,
                               WebSocketTemplate webSocketTemplate,
                               ApplicationEventPublisher eventPublisher, ApplicationContext applicationContext) {

        if (configurer == null) configurer = new DefaultWebSocketConfigurer() {
        };

        WebSocketConfig webSocketConfig = new WebSocketConfig(configurer, eventPublisher);

        WebSocketDispatch websocketDispatch = new WebSocketDispatch(webSocketConfig, applicationContext, webSocketTemplate);
        ExceptionDispatch exceptionDispatch = new ExceptionDispatch(applicationContext, webSocketTemplate);
        
        WebSocketServer socketServer = new WebSocketServer(webSocketConfig, websocketDispatch, exceptionDispatch);

        // 完善消息发布器配置
        webSocketTemplate.setServer(socketServer);
        webSocketTemplate.setConverter(webSocketConfig.converter);
        webSocketTemplate.setPublisher(webSocketConfig.eventPublisher);

        // 启动 websocket 服务
        socketServer.start();
    }

}
